<template>
  <div>
    <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽"></el-switch>
    <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId"
      :default-expanded-keys="expandedKey" :draggable="draggable" :allow-drop="allowDrop" @node-drop="handleDrop" ref="menuTree">
      <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span>
            <el-button
              v-if="node.level <= 2"
              type="text"
              size="mini"
              @click="() => append(data)">
              添加
            </el-button>
            <el-button
              v-if="node.level <= 2"
              type="text"
              size="mini"
              @click="() => edit(data)">
              修改
            </el-button>
            <el-button
              v-if="node.childNodes.length == 0"
              type="text"
              size="mini"
              @click="() => remove(node, data)">
              删除
            </el-button>
          </span>
        </span>
    </el-tree>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "category",

  data() {
    return {
      pCid: 0,
      draggable: false,
      updateNodes: [],
      maxlevel: 0,
      title: '',
      dialogType: '',
      category: {},
      menus: [],
      expandedKey: [2],
      dialogVisible: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    };
  },

  created() {
    this.getMenuInfos()
  },

  methods: {
    getMenuInfos () {
      this.$http({
        url: this.$http.adornUrl('/gmmallproduct/category/list/tree'),
        method: 'get'
      }).then(({data}) => {
        this.menus = data.data
      })
    },

    allowDrop(draggingNode, dropNode, type) {
      this.countNodeLevel(draggingNode)
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1
      if (type == 'inner') {
        return (deep + dropNode.level) <= 3
      }else {
        return (deep + dropNode.parent.level) <= 3
      }
    },

    countNodeLevel(node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxlevel) {
            this.maxLevel = node.childNodes[i].level
          }
          this.countNodeLevel(node.childNodes[i])
        }
      }
    },

    handleDrop(draggingNode, dropNode, dropType, ev) {
      let pCid = 0
      let siblings = null
      if (dropType == 'before' || dropType == 'after') {
        pCid = dropNode.parent.data.catId == undefined ? 0 : dropNode.parent.data.catId
        siblings = dropNode.parent.childNodes
      }else {
        pCid = dropNode.data.catId
        siblings = dropNode.childNodes
      }
      this.pCid = pCid

      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          let catLevel = draggingNode.level
          if (siblings[i].level != draggingNode.level) {
            catLevel = siblings[i].level
            this.updateChildNodeLevel(siblings[i])
          }
          this.updateNodes.push({catId: siblings[i].data.catId, sort: i, parentCid: pCid, catLevel: catLevel});
        }else {
          this.updateNodes.push({catId: siblings[i].data.catId, sort: i});
        }
      }
    },

    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var cNode = node.childNodes[i].data
          this.updateNodes.push({catId: cNode.catId, catLevel: node.childNodes[i].level})
          this.updateChildNodeLevel(node.childNodes[i])
        }
      }
    },

    batchDelete() {
      let catIds = []
      let checkNodes = this.$refs.menuTree.getCheckedNodes()
      for (let i = 0; i < checkNodes.length; i++) {
        catIds.push(checkNodes[i].catId)
      }
      this.$confirm(`是否批量删除[${catIds}]菜单`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/gmmallproduct/category/delete'),
          method: 'post',
          data: this.$http.adornData(catIds, false)
        }).then(({data}) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getMenuInfos()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    batchSave() {
      this.$http({
        url: this.$http.adornUrl('/gmmallproduct/category/update/sort'),
        method: 'post',
        data: this.$http.adornData(this.updateNodes,false)
      }).then(({data}) => {
        this.$message({
          type: 'success',
          message: '菜单顺序修改成功!'
        });
        this.getMenuInfos()
        this.expandedKey = [this.pCid]
        this.updateNodes = []
        this.maxLevel = 0
        this.pCid = 0
      })
    },

    submitData() {
      if (this.dialogType == 'add') {
        this.addCategory()
      }else if (this.dialogType == 'edit') {
        this.editCategory()
      }
    },

    append(data) {
      this.title = '添加商品'
      this.dialogType = 'add'
      this.dialogVisible = true
      this.category = {}
      this.category.parentCid = data.catId
      this.category.catLevel = data.catLevel * 1 + 1
    },

    edit(data) {
      this.title = '修改商品'
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.$http({
        url: this.$http.adornUrl(`/gmmallproduct/category/info/${data.catId}`),
        method: 'get'
      }).then(({data}) => {
        this.category = data.category
      })
    },

    editCategory() {
      var {catId, name, icon, productUnit} = this.category
      this.$http({
        url: this.$http.adornUrl('/gmmallproduct/category/update'),
        method: 'post',
        data: this.$http.adornData({catId, name, icon, productUnit},false)
      }).then(({data}) => {
        this.$message({
          type: 'success',
          message: '修改成功!'
        });
        this.dialogVisible = false
        this.getMenuInfos()
        this.expandedKey = [this.category.parentCid]
      })
    },

    addCategory() {
      this.category.showStatus = 1
      this.category.sort = 0
      this.$http({
        url: this.$http.adornUrl('/gmmallproduct/category/save'),
        method: 'post',
        data: this.$http.adornData(this.category,false)
      }).then(({data}) => {
        this.$message({
          type: 'success',
          message: '添加成功!'
        });
        this.dialogVisible = false
        this.getMenuInfos()
        this.expandedKey = [this.category.parentCid]
      })
    },

    remove(node, data) {
      var ids = [data.catId]
      this.$confirm('是否删除[' + data.name + ']菜单', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/gmmallproduct/category/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getMenuInfos()
          this.expandedKey = [node.parent.data.catId]
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

  }
}
</script>

<style scoped>

</style>
